#!/usr/bin/env python2.7
import subprocess
import urllib2
import hashlib

PKGBUILD_FORMAT = '''# Maintainer: Xiaodong Qi <qxd@bupt.edu.cn>
pkgname=yage
pkgver=0.1.0.{date}.{gitrev}
pkgrel=1
epoch=0
pkgdesc="Yet another Graphics Engine"
arch=('i686' 'x86_64')
url="https://github.com/yet-another-graphics-engine/YaGE/"
license=('LGPL3')
groups=()
depends=('gtk3' 'gstreamer0.10')
makedepends=('cmake')
checkdepends=()
optdepends=()
provides=()
conflicts=()
replaces=()
backup=()
options=()
install=
changelog=
_gitbuild='{gitbuild}'
source=("https://github.com/yet-another-graphics-engine/YaGE/archive/$_gitbuild.zip")
noextract=()
md5sums=('{md5sum}')

prepare() {{
	return 0
}}

build() {{
	cd YaGE-$_gitbuild
	cmake . -DCMAKE_INSTALL_PREFIX:PATH=/usr -DCMAKE_BUILD_TYPE=Release
	make
}}

check() {{
	return 0
}}

package() {{
	cd YaGE-$_gitbuild
	make DESTDIR="$pkgdir/" install
}}
'''

_SRCINFO_FORMAT = '''# Generated by makepkg 4.2.1 and YaGE aur.py
# {timestamp}
pkgbase = yage
	pkgdesc = Yet another Graphics Engine
	pkgver = 0.1.0.{date}.{gitrev}
	pkgrel = 1
	epoch = 0
	url = https://github.com/yet-another-graphics-engine/YaGE/
	arch = i686
	arch = x86_64
	license = LGPL3
	makedepends = cmake
	depends = gtk3
	depends = gstreamer0.10
	source = https://github.com/yet-another-graphics-engine/YaGE/archive/{gitbuild}.zip
	md5sums = {md5sum}

pkgname = yage
'''

if __name__ == '__main__':
    aur_info = {}
    aur_info['gitbuild'] = subprocess.check_output('git rev-parse HEAD', shell=True)[:-1]
    aur_info['gitrev'] = subprocess.check_output('git rev-parse --short HEAD', shell=True)[:-1]
    zipball_address = "https://github.com/yet-another-graphics-engine/YaGE/archive/%s.zip" % aur_info['gitbuild']
    zipball_request = urllib2.urlopen(zipball_address)
    aur_info['md5sum'] = hashlib.md5(zipball_request.read()).hexdigest()
    zipball_request.close()
    aur_info['date'] = subprocess.check_output('TZ=Asia/Shanghai date +%Y%m%d.%H%M --date=@`git log HEAD -1 --format=%ct`', shell=True)[:-1]
    aur_info['timestamp'] = subprocess.check_output('LC_ALL=C date -u --date=@`git log HEAD -1 --format=%ct`', shell=True)[:-1]
    with open('PKGBUILD', 'wb') as pkgbuild_file:
        pkgbuild_file.write(PKGBUILD_FORMAT.format(**aur_info))
    with open('.SRCINFO', 'wb') as _srcinfo_file:
        _srcinfo_file.write(_SRCINFO_FORMAT.format(**aur_info))
